package com.why.controller;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageInfo;
import com.why.pojo.Product;
import com.why.pojo.User;
import com.why.service.ProductService;
import com.why.service.UserService;
import com.why.utils.FtpUtil;
import com.why.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.concurrent.TimeUnit;

@RestController
public class UserController {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private UserService userService;

    //获得用户信息
    @RequestMapping(value = "userinfo",produces = "application/json;charset=utf-8")
    public HashMap<String,Object> userinfo(HttpServletRequest request){
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie:cookies){
            if (cookie.getName().equals("cookieUser")){
                HashMap<String,Object> redisMap = (HashMap<String, Object>) redisTemplate.opsForValue().get(cookie.getValue());
                return redisMap;
            }
        }
        return null;
    }

    //修改自己用户信息
    @RequestMapping("/updateUser")
    public String updateUser(User user,HttpServletRequest request){
        Cookie[] cookies = request.getCookies();
        HashMap<String, Object> map = new HashMap<>();

        for (Cookie cookie:cookies){
            if (cookie.getName().equals("cookieUser")){
                HashMap<String,Object> redisMap = (HashMap<String, Object>) redisTemplate.opsForValue().get(cookie.getValue());
                User redisUser = (User) redisMap.get("user");

                if (user.getPassword()!=null && user.getPassword()!=""){
                    user.setPassword(SecurityUtils.md5Hex3(user.getPassword()));
                }else {
                    user.setPassword(redisUser.getPassword());
                }

                user.setId(redisUser.getId());
                user.setSex(redisUser.getSex());
                user.setType(redisUser.getType());
                user.setHeadPortrait(redisUser.getHeadPortrait());
                map.put("user",user);
                map.put("time",new Date());
                if (userService.updateByPrimaryKeySelective(user)){
                    redisTemplate.opsForValue().set(cookie.getValue(),map,30, TimeUnit.MINUTES);
                    return "success";
                }
            }
        }
        return "failed";
    }

    //修改密码时判断用户的原密码是否输入正确
    @RequestMapping("/password")
    public String password(HttpServletRequest request,String password){
        String newPassword=SecurityUtils.md5Hex3(password);
        User redisUser = userData(request);
        if (redisUser.getPassword().equals(newPassword)){
            return "success";
        }
        return "failed";
    }

    //分页查询所有用户
    @RequestMapping("/getPageUser")
    public PageInfo<User> getPageUser(Integer pageNum, Integer pageSize){
        return userService.getPageInfo(pageNum,pageSize);
    }

    //新增用户
    @RequestMapping("/addUser")
    public String addUser(User user){
        if (userService.insertSelective(user)){
            return "success";
        }
        return "failed";
    }

    //根据id查询用户
    @RequestMapping("/findUserById")
    public User findUserById(Integer id){
        return userService.selectByPrimaryKey(id);
    }

    //删除用户
    @RequestMapping("/deleteUser")
    public String deleteUser(Integer id){
        if (userService.deleteByPrimaryKey(id)){
            return "success";
        }
        return "failed";
    }

    //修改所有用户信息
    @RequestMapping("/updateAllUser")
    public String updateAllUser(User user){
        if (userService.updateByPrimaryKeySelective(user)){
            return "success";
        }
        return "failed";
    }

    //密码重置
    @RequestMapping("/resetPassword")
    public String resetPassword(Integer id){
        if (userService.updatePassword(id)){
            return "success";
        }
        return "failed";
    }

    //上传用户头像
    @RequestMapping(value = "/uploading",produces = "application/json;charset=utf-8")
    public Object uploading(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws IOException {
        //获取上传的文件流
        InputStream inputStream=file.getInputStream();
        //获取上传的文件名
        String fileName=file.getOriginalFilename();
        System.out.println(fileName);
        //截取后缀
        String suffix=fileName.substring(fileName.lastIndexOf("."));
        //使用时间戳拼接后缀，生成一个不重复的文件名
        String newFileName=System.currentTimeMillis()+suffix;

        //调用自定义的FTP工具类上传文件
        boolean b = FtpUtil.uploadFile(newFileName, inputStream);
        Cookie[] cookies = request.getCookies();
        User user = null;
        String cookieId="";
        for(Cookie cookie : cookies){
            if (cookie.getName().equals("cookieUser")){
                HashMap<String,Object> map = (HashMap<String, Object>) redisTemplate.opsForValue().get(cookie.getValue());
                user = (User) map.get("user");
                cookieId=cookie.getValue();
            }
        }
        HashMap<String, Object> map = new HashMap<>();
        if (b){
            user.setHeadPortrait(newFileName);
            userService.updateImag(user);
            HashMap<String, Object> redisMap = new HashMap<>();
            redisMap.put("user",user);
            redisMap.put("time",new Date());
            redisTemplate.opsForValue().set(cookieId,redisMap,30,TimeUnit.MINUTES);
            map.put("status","success");
            map.put("fileName",user.getHeadPortrait());
            return JSON.toJSONString(map);
        }
        map.put("status","failed");
        return JSON.toJSONString(map);
    }


    //获取用户信息，由于本类调用
    public User userData(HttpServletRequest request){
        Cookie[] cookies = request.getCookies();
        //redis
        User user = null;
        for(Cookie cookie : cookies){
            if (cookie.getName().equals("cookieUser")){
                HashMap<String,Object> map = (HashMap<String, Object>) redisTemplate.opsForValue().get(cookie.getValue());
                user = (User) map.get("user");
            }
        }
        return user;
    }
}
